<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { FormInstance, UploadFile } from 'element-plus'
  import { orderAnnexUpload } from '@/api/upload'
  import { saveRemark } from '@/api/order'
  import { OrderAPIRequestParam } from '@/typings/api/order'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    workIds: {
      type: Array<string>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  // 表单验证规则
  const rules = ref({
    note: [
      {
        required: true,
        message: '请输入工单回复',
        trigger: ['blur', 'change'],
      },
    ],
    visitTypes: [
      {
        required: true,
        message: '请选择可见类型',
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 弹窗状态
  const visible = ref(false)

  /**
   * 关闭事件
   */
  const onClose = () => {
    form.value = {
      note: '',
      fileList: [],
      visitTypes: [0],
    }
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  // 表单
  const form = ref<{ note: string; fileList: Array<UploadFile>; visitTypes }>({
    note: '',
    fileList: [],
    visitTypes: [0],
  })

  /**
   * 移除图片事件
   * @param {object} file - 文件
   */
  // const handleRemove = (file: UploadFile) => {
  //   const index = form.value.fileList.findIndex((item) => item.url === file.url)
  //   form.value.fileList.splice(index, 1)
  // }

  /**
   * 文件上传
   * @param {object} file - 文件
   */
  // const handleChange = (file: UploadFile) => {
  //   const fileReader = new FileReader()
  //   fileReader.readAsDataURL(file.raw)
  //   fileReader.onload = () => {
  //     if (form.value.fileList.length + 1 > 5) {
  //       ElMessage({
  //         type: 'error',
  //         message: '最多只能上传5张图片',
  //       })
  //       return false
  //     }
  //     form.value.fileList.push(Object.assign(file, { url: fileReader.result }))
  //   }
  // }

  // form组件实例
  const formRef = ref<FormInstance | null>(null)

  // 保存加载
  const saveLoading = ref(false)

  /**
   * 确定事件
   */
  const onConfirm = () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          saveLoading.value = true
          const data: OrderAPIRequestParam.SaveOrderRemark = {
            annexs: [],
            remark: '',
            workIds: [],
            visitTypes: [0],
          }

          data.remark = form.value.note
          data.workIds = props.workIds
          data.visitTypes = form.value.visitTypes

          for (let i = 0; i < form.value.fileList.length; i++) {
            const res = await orderAnnexUpload([form.value.fileList[i].raw])
            data.annexs.push(res.data.data.rows[0])
          }

          const saveResult = await saveRemark(data)
          if (saveResult.data.success) {
            HMessage.success('保存成功')
          } else {
            HMessageBox.error(saveResult.data.message)
          }
          if (saveResult.data.success) {
            visible.value = false
            emits('update:modelValue', visible.value)

            form.value = {
              note: '',
              fileList: [],
              visitTypes: [0],
            }
            emits('update')
          }
          saveLoading.value = false
        }
      })
    }
  }

  watch(
    () => props.modelValue,
    (value) => {
      visible.value = value
    },
  )
</script>

<template>
  <h-dialog v-model="visible" title="填写工单回复" @close="onClose">
    <div class="title">
      <span>当前选中</span>
      <span class="num">{{ props.workIds.length }}</span>
      <span>个工单进行批量填写工单回复！</span>
    </div>
    <el-form
      ref="formRef"
      v-loading="saveLoading"
      label-width="70"
      :rules="rules"
      :model="form"
      class="modal_form_content"
      label-position="top"
    >
      <!--工单回复-->
      <el-form-item label="工单回复" prop="note" class="form_textarea_item">
        <el-input
          v-model="form.note"
          type="textarea"
          placeholder="请填写工单回复"
          maxlength="200"
          show-word-limit
          resize="both"
        />
      </el-form-item>

      <!--可见类型-->
      <!-- <el-form-item prop="visitTypes" class="form_checkbox_group_item" label="可见类型">
        <el-checkbox-group v-model="form.visitTypes" class="visit_type">
          <el-checkbox :value="0">
            <span class="visit_type_text">公开</span>
          </el-checkbox>
          <el-checkbox :value="1">
            <span class="visit_type_text">服务商可见</span>
          </el-checkbox>
          <el-checkbox :value="2">
            <span class="visit_type_text">工程师可见</span>
          </el-checkbox>
          <el-checkbox :value="3">
            <span class="visit_type_text">客户可见</span>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" :loading="saveLoading" @click="onConfirm">确定</h-button>
      <h-button is-modal :loading="saveLoading" @click="onClose">关闭</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  :deep(.el-form-item__error) {
    padding-top: 4px;
  }

  :deep(.el-textarea) {
    .el-textarea__inner {
      height: 200px !important;
      width: 100% !important;
      overflow: hidden;
    }
  }

  .title {
    margin-bottom: 12px;

    .num {
      color: $secondColor2;
    }
  }

  .visit_type {
    display: flex;
    justify-content: space-between;
  }

  .img_container {
    display: flex;
    gap: 5px;

    .upload_container {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    :deep(.el-upload) {
      width: 50px;
      height: 50px;
    }

    .tip {
      font-size: 12px;
      color: #a8abb2;
    }

    .imgs {
      display: flex;
      gap: 5px;
      flex-wrap: wrap;

      .img_box {
        cursor: pointer;
        position: relative;

        .img {
          width: 50px;
          height: 50px;
          border-radius: 4px;
        }

        .operate {
          border-radius: 4px;
          background-color: rgba(#000, 0.3);
          width: 50px;
          height: 50px;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
          justify-content: space-around;
          color: #fff;
          opacity: 0;
          transition: all 0.2s ease-in-out;
        }

        &:hover .operate {
          opacity: 1;
        }
      }
    }
  }
</style>
